/**
 * 
 */
package com.res.simulator.handler;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * @author Dhanushka Ariyasingha.
 * 
 */
public class CommonFileHandler {

	private String location = null;

	public CommonFileHandler() {

		// TODO : Location need to be read from property file.

		location = System.getProperty("user.dir") + "/";
	}

	public String save(final String xml, final String fileName) {

		final String fileUrl = location.concat(fileName);

		System.out.println("File name and location");
		System.out.println("Name : " + fileName);
		System.out.println("Location : " + location);

		try {

			final OutputStreamWriter writer = new OutputStreamWriter(
					new FileOutputStream(fileUrl));
			writer.write(xml);
			writer.close();

		} catch (final IOException ioe) {

			System.out.println("IO error: " + ioe);
		}

		return fileUrl;
	}

	public StringBuilder read(final String fileLocation) throws FileNotFoundException {

		final StringBuilder stringBuilder = new StringBuilder();

		try {

			final FileInputStream fstream = new FileInputStream(fileLocation);
			final DataInputStream in = new DataInputStream(fstream);
			final BufferedReader reader = new BufferedReader(new InputStreamReader(in));

			String strLine;

			while ((strLine = reader.readLine()) != null) {

				stringBuilder.append(strLine);

			}

			in.close();

		} catch (final Exception exception) {// Catch exception if any
			exception.printStackTrace();
		}

		return stringBuilder;
	}
}
